package api

import (
	"net/http"
	"strconv"

	"erp/config"
	"erp/logic"
	"erp/model"

	"github.com/gin-gonic/gin"
)

func RegisterProductRoutes(r *gin.Engine) {
	s := logic.ProductService{DB: config.DB}

	// 产品列表
	r.GET("/products", func(c *gin.Context) {
		list, err := s.List()
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, list)
	})

	// 获取单个产品
	r.GET("/products/:id", func(c *gin.Context) {
		id64, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		p, err := s.Get(uint(id64))
		if err != nil {
			c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, p)
	})

	// 创建产品
	r.POST("/products", func(c *gin.Context) {
		var p model.Product
		if err := c.ShouldBindJSON(&p); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		if err := s.Create(&p); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, p)
	})

	// 更新产品
	r.PUT("/products/:id", func(c *gin.Context) {
		id64, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		var in model.Product
		if err := c.ShouldBindJSON(&in); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		p, err := s.Update(uint(id64), &in)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, p)
	})

	// 删除产品
	r.DELETE("/products/:id", func(c *gin.Context) {
		id64, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		if err := s.Delete(uint(id64)); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.Status(http.StatusNoContent)
	})

	// 库存调整
	r.POST("/products/:id/stock", func(c *gin.Context) {
		id64, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		var req struct {
			Quantity int    `json:"quantity"`
			Type     string `json:"type"` // "in" 或 "out"
			Notes    string `json:"notes"`
		}
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		if err := s.AdjustStock(uint(id64), req.Quantity, req.Type, req.Notes); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "库存调整成功"})
	})

	// 产品搜索
	r.GET("/products/search", func(c *gin.Context) {
		query := c.Query("q")
		if query == "" {
			c.JSON(http.StatusBadRequest, gin.H{"error": "搜索关键词不能为空"})
			return
		}
		products, err := s.Search(query)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, products)
	})
}
